<script setup>
import { ref } from 'vue'
import api from '@/api'
import { parsePage, parseQuery } from '@/utils'
import { useRoute, useRouter } from 'vue-router'
import { Modal } from '@arco-design/web-vue'
import uploadImage from '@/components/uploadImage.vue'

const $route = useRoute()
const $router = useRouter()

// const listFormData = ref({
//   page: parsePage($route.query.page, 1),
//   keyword: $route.query.keyword || '',
//   category: '',
// })
const keyword = ref('')
const category = ref('')
const pageVal = ref(1)
const pageSize = ref(10)
const listData = ref([])
const listTotal = ref(0)
const listLoading = ref(false)

const getListData = async (page = 1) => {
  listLoading.value = true
  try {
    // listFormData.value.page = page
    // const query = parseQuery(listFormData.value)
    // $router.replace({ query })
    const res = await api.get('ip/materials', {
      params: {
        keyword: keyword.value,
        category: category.value,
        page,
        pageSize: pageSize.value,
      },
    })
    listData.value = res.data.data
    listTotal.value = res.data.total
    pageVal.value = page
  } catch (error) {
    console.error(error)
  }
  listLoading.value = false
}

const resetListData = () => {
  // listFormData.value.keyword = ''
  // listFormData.value.category = ''
  keyword.value = ''
  category.value = ''
  getListData()
}

getListData()

const formRef = ref()
const formItem = ref()
const formLoading = ref(false)
const formVisible = ref(false)
const formData = ref({
  category: '',
  title: '',
  image: '',
  from: '',
  link: '',
  content: '',
})
const formRules = {
  category: [
    {
      required: true,
      message: '请选择分类',
    },
  ],
  title: [
    {
      required: true,
      message: '请填写素材标题',
    },
  ],
  image: [
    {
      required: true,
      message: '请上传素材封面',
    },
  ],
  from: [
    {
      required: true,
      message: '请输入素材来源',
    },
  ],
  link: [
    {
      required: true,
      message: '请输入素材链接',
    },
  ],
  content: [
    {
      required: true,
      message: '请填写素材内容',
    },
  ],
}

const create = () => {
  formRef.value?.resetFields()
  formVisible.value = true
}

const update = (item) => {
  formRef.value?.resetFields()
  formItem.value = item
  formData.value.title = item.title
  formData.value.category = item.category
  formData.value.image = item.image
  formData.value.content = item.content
  formData.value.from = item.from
  formData.value.link = item.link
  formVisible.value = true
}

const categories = ref([])
const categoriesLoading = ref(false)

const formSubmit = async () => {
  if (await formRef.value.validate()) {
    return false
  }

  formLoading.value = true

  try {
    if (formItem.value) {
      await api.put('ip/materials/' + formItem.value.id, formData.value)
    } else {
      await api.post('ip/materials', formData.value)
    }
    formRef.value?.resetFields()
    formVisible.value = false
    getListData()
  } catch (error) {
    console.error(error)
  }

  formLoading.value = false

  return false
}

const del = (item) => {
  Modal.confirm({
    title: '删除素材',
    content: '您确定要删除吗？',
    bodyStyle: 'text-align:center',
    onBeforeOk: async () => {
      await api.delete('ip/materials/' + item.id)

      getListData()
    },
  })
}

const getCategories = async () => {
  categoriesLoading.value = true
  try {
    const res = await api.get('ip/materials/categories/options')
    categories.value = res.data
  } catch (error) {
    console.error(error)
  }
  categoriesLoading.value = false
}

getCategories()
</script>

<template>
  <div class="page">
    <div class="header">
      <a-space>
        <a-button type="primary"
                  @click="create">添加素材</a-button>
      </a-space>
      <a-form class="page-form"
              layout="inline"
              @submit="getListData()">
        <a-space>
          <a-select v-model="category"
                    value-key="id"
                    allow-clear
                    allow-search
                    placeholder="分类">
            <template #label="{ data }">
              <div class="has-image">
                <div class="img">
                  <img :src="data?.value.image" />
                </div>
                <div class="label">{{ data?.value.name }}</div>
              </div>
            </template>
            <a-option class="has-image"
                      v-for="(item,index) in categories"
                      :value="item"
                      :key="index"
                      :id="item.id">
              <div class="img">
                <img :src="item.image" />
              </div>
              <div class="label">{{ item.name }}</div>
            </a-option>
          </a-select>
          <a-input v-model.trim="keyword"
                   placeholder="标题"
                   allow-clear />

          <a-button type="primary"
                    html-type="submit">
            <template #icon>
              <icon-search />
            </template>
            查询
          </a-button>

          <a-button @click="resetListData">
            <template #icon>
              <icon-refresh />
            </template>重置
          </a-button>
        </a-space>
      </a-form>
    </div>

    <a-table :loading="listLoading"
             :data="listData"
             @page-change="getListData"
             :pagination="{
              showTotal: true,
              size: 'small',
              total: listTotal,
              pageSize: pageSize,
              current: pageVal,
            }">
      <template #columns>
        <a-table-column title="序号"
                        :width="60">
          <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
        </a-table-column>
        <a-table-column title="分类"
                        :width="200">
          <template #cell="{ record }">
            <div style="display: flex; align-items: center">
              <div class="cell-img"
                   style="width: 30px; height: 30px; margin-right: 5px">
                <img :src="record.category.image" />
              </div>
              <div>{{ record.category.name }}</div>
            </div>
          </template>
        </a-table-column>
        <a-table-column title="封面"
                        :width="200">
          <template #cell="{ record }">
            <div class="cell-img"
                 style="width: 135px; height: 170px">
              <img :src="record.image" />
            </div>
          </template>
        </a-table-column>
        <a-table-column title="标题"
                        data-index="title"></a-table-column>
        <a-table-column title="来源"
                        data-index="from"></a-table-column>
        <a-table-column title="链接"
                        data-index="link"></a-table-column>
        <a-table-column title="内容"
                        data-index="content">
          <template #cell="{ record }">
            <!-- <div
              class="content"
              style="width: 400px; word-break: break-all; white-space: pre-wrap"
            >
              {{ record.content }}
            </div> -->
            <a-typography-paragraph class="text-ellipsis"
                                    style="width: 400px; word-break: break-all; white-space: pre-wrap"
                                    :ellipsis="{
                rows: 5,
                expandable: true,
              }">{{ record.content }}</a-typography-paragraph>
          </template>
        </a-table-column>
        <a-table-column title="添加时间"
                        data-index="created_at"></a-table-column>
        <a-table-column align="right"
                        :width="88">
          <template #cell="{ record }">
            <a-space>
              <a-button type="primary"
                        size="mini"
                        @click="update(record)">编辑</a-button>
              <a-button type="primary"
                        status="danger"
                        size="mini"
                        @click="del(record)">
                删除
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <a-modal v-model:visible="formVisible"
             :title="(formItem ? '编辑' : '添加') + '素材'"
             width="800px"
             :ok-loading="formLoading"
             :on-before-ok="formSubmit">
      <a-form ref="formRef"
              :model="formData"
              :rules="formRules">
        <a-form-item field="image"
                     label="封面"
                     help="请上传jpg、png、gif格式图片、文件大小不能超过1MB"
                     validate-trigger="input"
                     style="margin-bottom: 10px">
          <uploadImage v-model="formData.image"
                       width="200px"
                       height="200px"></uploadImage>
        </a-form-item>
        <a-form-item field="category"
                     label="分类">
          <a-select v-model="formData.category"
                    value-key="id"
                    allow-clear
                    allow-search>
            <template #label="{ data }">
              <div class="has-image">
                <div class="img">
                  <img :src="data?.value.image" />
                </div>
                <div class="label">{{ data?.value.name }}</div>
              </div>
            </template>
            <a-option class="has-image"
                      v-for="(item,index) in categories"
                      :value="item"
                      :id="item.id"
                      :key="index">
              <div class="img">
                <img :src="item.image" />
              </div>
              <div class="label">{{ item.name }}</div>
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="title"
                     label="标题">
          <a-input v-model="formData.title"
                   allow-clear />
        </a-form-item>
        <a-form-item field="from"
                     label="来源">
          <a-input v-model="formData.from"
                   allow-clear />
        </a-form-item>
        <a-form-item field="link"
                     label="链接">
          <a-input v-model="formData.link"
                   allow-clear />
        </a-form-item>
        <a-form-item field="content"
                     label="内容">
          <a-textarea v-model="formData.content"
                      :max-length="{ length: 1000, errorOnly: true }"
                      allow-clear
                      show-word-limit
                      :auto-size="{ minRows: 8 }" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped></style>
